package com.mlm.mlmapp.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DrawableRes;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.Constants;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CircleImageView;
import com.mlm.mlmapp.utils.CommonUtils;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.comment_submit)
public class CommentSubmitActivity extends BaseActivity implements HTTPCons {
	AQuery aq;
	AjaxCallback<JSONObject> submitCB;
	@ColorRes
	int red;
	@ColorRes
	int lightgreytext;
	@ColorRes
	int blacktext;
	@DrawableRes
	Drawable red_edge_btn_long;
	@DrawableRes
	Drawable grey_edge_btn_long;
	@StringRes
	String take_photo;
	@StringRes
	String from_photos;
	@ColorRes
	int white;
	@DrawableRes
	Drawable comment_level_selected_bottom;
	@DrawableRes
	Drawable best_def;
	@DrawableRes
	Drawable good_def;
	@DrawableRes
	Drawable normal_def;
	@DrawableRes
	Drawable best_sel;
	@DrawableRes
	Drawable good_sel;
	@DrawableRes
	Drawable normal_sel;
	@Pref
	Prefs_ pref;
	@ViewById
	Button btn_next;
	@ViewById
	Button best;
	@ViewById
	Button good;
	@ViewById
	Button normal;
	@ViewById
	LinearLayout items;
	@ViewById
	TextView tv_name;
	@ViewById
	CircleImageView iv_headimg;
	@ViewById
	EditText tv_comments;
	@ViewById
	ImageView iv_first;
	@ViewById
	ImageView iv_second;
	@ViewById
	ImageView iv_third;
	@Extra
	String orderid;
	@Extra
	String dresserid;
	private String fphoto = "";
	private String sphoto = "";
	private String tphoto = "";
	private Bitmap photo;
	public static final String IMAGE_FILE_NAME = "comment.jpg";
	
	private int level = 1;

	//
	// @CheckedChange
	// void best(boolean isChecked) {
	// if (isChecked) {
	// level = 1;
	// }
	// }
	//
	// @CheckedChange
	// void good(boolean isChecked) {
	// if (isChecked) {
	// level = 2;
	// }
	// }
	//
	// @CheckedChange
	// void normal(boolean isChecked) {
	// if (isChecked) {
	// level = 3;
	// }
	// }

	@Click
	void btn_next() {
		commentAction();
	}

	float oldx = 0;
	private ActionSheetDialog dialog;

	@AfterViews
	void init() {
		String title = getTitle().toString();
		if (!"".equals(title)) {
			((TextView) this.findViewById(R.id.tv_title)).setText(title);
		}

		if (orderid == null) {
			orderid = "";
		}
		if (dresserid == null) {
			dresserid = "";
		}
		btn_next.setClickable(false);
		iv_first.setTag(1);
		iv_second.setTag(2);
		iv_third.setTag(3);
		tv_comments.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s.length() > 0) {
					btn_next.setTextColor(red);
					btn_next.setBackground(red_edge_btn_long);

					btn_next.setClickable(true);
				} else {
					btn_next.setTextColor(lightgreytext);
					btn_next.setBackground(grey_edge_btn_long);
					btn_next.setClickable(false);
				}
			}
		});
		// rating.setRating(1);
		// rating.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
		//
		// @Override
		// public void onRatingChanged(RatingBar ratingBar, float rating,
		// boolean fromUser) {
		// // TODO Auto-generated method stub
		// if (rating < 1f) {
		// ratingBar.setRating(1);
		// }
		// }
		// });

		// rating.setOnTouchListener(new OnTouchListener() {
		//
		// @Override
		// public boolean onTouch(View v, MotionEvent event) {
		// // TODO Auto-generated method stub
		// if (event.getAction() == 0)
		// oldx = event.getX();
		// if (event.getAction() == 1) {
		// if (Math.abs((event.getX() - oldx)) > 1) {
		// return true;
		// }
		// }
		// if (event.getAction() == 2) {
		// return true;
		// }
		// return false;
		// }
		// });
		aq = new AQuery(this);
		submitCB = new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject html, AjaxStatus status) {

				if (status.getCode() == -101) {
					Toast.makeText(CommentSubmitActivity.this, "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_LONG).show();
				} else {
					
					try {
						if (html.getBoolean("isSuccess")) {

							Toast.makeText(aq.getContext(), "评价成功",
									Toast.LENGTH_LONG).show();
							CommentSubmitActivity.this.finish();
						} else {
							Toast.makeText(aq.getContext(),
									html.getString("errors"), Toast.LENGTH_LONG)
									.show();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		};
		getDresserByid();
	}

	private void commentAction() {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("mobile", pref.loginID().get()));
		pairs.add(new BasicNameValuePair("stylistId", dresserid));
		pairs.add(new BasicNameValuePair("starLevel", level + ""));
		pairs.add(new BasicNameValuePair("content", tv_comments.getText()
				.toString()));
		pairs.add(new BasicNameValuePair("orderId", orderid));
		pairs.add(new BasicNameValuePair("fphoto", fphoto));
		pairs.add(new BasicNameValuePair("sphoto", sphoto));
		pairs.add(new BasicNameValuePair("tphoto", tphoto));
		CommonUtils.postRequest(submit_comment, aq, submitCB, pairs);
	}

	private void getDresserByid() {
		String url = get_dresser_detail_action + dresserid + "&mobile="
				+ pref.loginID().get();
		aq.progress(new AQProgressDialog(this)).ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject object,
								 AjaxStatus status) {
				if (status.getCode() == -101) {
					Toast.makeText(aq.getContext(), "网络异常,请检查网络",
							Toast.LENGTH_SHORT);
					return;
				}
				// TODO Auto-generated method stub
				if (status.getCode() != 200) {
					Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
							Toast.LENGTH_LONG).show();
				} else {

					aq.id(iv_headimg).image(
							getJsonString(object, "iconPhotoUrl"), true, true,
							0, 0, null, Constants.FADE_IN);
					tv_name.setText(getJsonString(object, "name"));

				}
			}

		});
	}

	@Click
	void iv_first(View v) {
		this.num = (int) v.getTag();
		dialog = new ActionSheetDialog(this, new String[] { take_photo,
				from_photos }, null);
		dialog.titleTextColor(red).itemTextColor(blacktext).cornerRadius(0)
				.show();
		dialog.setOnOperItemClickL(new OnOperItemClickL() {
			@Override
			public void onOperItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				switch (position) {
				case 0:
					Intent intentFromCapture = new Intent(
							MediaStore.ACTION_IMAGE_CAPTURE);
					// 判断存储卡是否可以用，可用进行存储
					intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
							.fromFile(new File(Environment
									.getExternalStorageDirectory(),
									IMAGE_FILE_NAME)));
					startActivityForResult(intentFromCapture,
							AVATAR_REQUEST_CODE);

					break;
				case 1:
					Intent intentFromGallery = new Intent();
					intentFromGallery.setType("image/*"); // 设置文件类型
					intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(intentFromGallery,
							GALLERY_AVATAR_REQUEST_CODE);
					break;
				}
				dialog.dismiss();
			}
		});
	}

	@OnActivityResult(GALLERY_AVATAR_REQUEST_CODE)
	void onResultGallery(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (data != null) {
			Intent intent = CommonUtils.startPhotoZoom(data.getData());
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		}
	}

	@OnActivityResult(AVATAR_REQUEST_CODE)
	void onResultTakeAvatar(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		File tempFile = new File(Environment.getExternalStorageDirectory(),
				IMAGE_FILE_NAME);
		Intent intent = CommonUtils.startPhotoZoom(Uri.fromFile(tempFile));
		startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}

	@OnActivityResult(PHOTO_PICKED_WITH_DATA)
	void onResultGetAvatar(int resultCode, Intent data) {
		if (resultCode == RESULT_CANCELED) {
			return;
		}
		if (data != null) {
			setImageToView(data);
		}
		if (iv_second.getVisibility() == View.GONE)
			iv_second.setVisibility(View.VISIBLE);
		else {
			iv_third.setVisibility(View.VISIBLE);
		}
	}

	private void setImageToView(Intent data) {
		Bundle extras = data.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			try {

				switch (num) {
				case 1:
					iv_first.setImageBitmap(photo);
					fphoto = CommonUtils.encodeBase64File(CommonUtils
							.saveBitmap(photo));
					break;
				case 2:
					iv_second.setImageBitmap(photo);
					sphoto = CommonUtils.encodeBase64File(CommonUtils
							.saveBitmap(photo));
					break;
				case 3:
					iv_third.setImageBitmap(photo);
					tphoto = CommonUtils.encodeBase64File(CommonUtils
							.saveBitmap(photo));
					break;

				default:
					break;
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// uploadAction(temp);
		}
	}

	@Click
	void best() {
		checked(best,best_sel,10);
		unchecked(good,good_def,25);
		unchecked(normal,normal_def,25);
		level=1;
	}

	@Click
	void good() {
		checked(good,good_sel,25);
		unchecked(best,best_def,10);
		unchecked(normal,normal_def,25);
		level=2;
	}

	@Click
	void normal() {
		checked(normal,normal_sel,25);
		unchecked(good,good_def,25);
		unchecked(best,best_def,10);
		level=3;
	}
	private void unchecked(Button b,Drawable d,int padding){
		b.setBackground(null);
		b.setCompoundDrawablesWithIntrinsicBounds(d,null, null, null);
		b.setPadding(CommonUtils.dip2px(this, padding), CommonUtils.dip2px(this, 5), 0, CommonUtils.dip2px(this, 5));
		b.setCompoundDrawablePadding(-CommonUtils.dip2px(this, padding));
		b.setTextColor(lightgreytext);
	}
	private void checked(Button b,Drawable d,int padding){
		b.setBackground(comment_level_selected_bottom);
		b.setCompoundDrawablesWithIntrinsicBounds(d,null, null, null);
		b.setPadding(CommonUtils.dip2px(this, padding), CommonUtils.dip2px(this, 5), 0, CommonUtils.dip2px(this, 5));
		b.setCompoundDrawablePadding(-CommonUtils.dip2px(this, padding));
		b.setTextColor(white);
	}
	@Click
	void iv_second(View v) {
		iv_first(v);
	}

	@Click
	void iv_third(View v) {
		iv_first(v);
	}

	private int num = 0;

	@Click
	void btn_back() {
		onBackPressed();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		Intent data = new Intent();
		setResult(RESULT_CANCELED, data);
		this.finish();
	}
}
